﻿using QunProject.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QunProject.Manage.Controllers
{
    public class ClassifyController : BaseController
    {
        // 首页
        public ActionResult Index()
        {
            return View();
        }
        // 编辑页
        public ActionResult Edit(int? id)
        {
            ViewBag.ID = id;
            return View();
        }
        // 获取数据
        public JsonResult AjaxData()
        {
            var list = EF.classify.Where(x => true);

            var data = list.ToList().Select(x => new
            {
                x.ID,
                CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                x.Remark,
                x.Name,
                x.Types
            });

            return Json(Result.SuccessReturnData(list.Count(), data));
        }
        // 提交编辑
        public JsonResult AjaxEdit(Model.classify model)
        {
            Model.classify _model = new Model.classify();
            if (model.Name.IsNullOrWhiteSpace())
                return Json(Result.Fail("名称不能为空"));

            if (model.ID > 0)
            {
                _model = EF.classify.SingleOrDefault(x => x.ID == model.ID);
                _model = EF.classify.Attach(_model);
                _model.Name = model.Name;
                _model.Remark = model.Remark;
                _model.Types = model.Types;
            }
            else
            {
                _model = EF.classify.SingleOrDefault(x => x.Name == model.Name);
                if (_model != null)
                    return Json(Result.Fail("已存在此分类"));
                else
                    _model = new Model.classify();

                _model.CreateTime = DateTime.Now;
                _model.Types = model.Types;
                _model.Name = model.Name;
                _model.Remark = model.Remark;
            }

            bool isSucc = false;
            if (model.ID > 0)
            {
                isSucc = EF.SaveChanges() > 0;
            }
            else
            {
                EF.classify.Add(_model);
                isSucc = EF.SaveChanges() > 0;
            }
            return isSucc ? Json(Result.Success()) : Json(Result.Fail());
        }
        // 查询实体
        public JsonResult AjaxEntity(int id)
        {
            var model = EF.classify.SingleOrDefault(x => x.ID == id);
            if (model == null)
                return Json(Result.Fail("不存在此分类"));
            return Json(Result.Success(model));
        }
    }
}